const EggService = require('egg').Service
const dayjs = require('dayjs')

class Controller extends EggService {
  // 登录
  async login() {
    const { ctx } = this
    const { body } = ctx.request

    const { user, token, exp, expireTime } = await this.service.userAccount.login({
      ...body,
      autoRegister: true,
    })

    ctx.session.user = user

    ctx.body = {
      code: 0,
      msg: '登录成功',
      data: {
        user,
        token,
        exp,
        expireTime,
      },
    }
  }

  // 刷新Token
  async refreshToken() {
    const { ctx } = this

    const { user, token, expireTime } = await this.service.userAccount.login(null, {
      _id: ctx.state.user.id,
    })

    ctx.session.user = user

    ctx.body = {
      code: 0,
      msg: 'success',
      data: {
        userId: user.id,
        token,
        expireTime,
      },
    }
  }

  // 刷新
  async logout() {
    const { ctx } = this

    ctx.body = {
      code: 0,
      msg: '退出成功',
    }
  }

  // 用户信息
  async getUserInfo() {
    const { ctx } = this

    const user = await this.service.user.getUserInfo(ctx.state.user.id)

    ctx.body = {
      code: 0,
      msg: 'success',
      data: user,
    }
  }

  // 用户信息
  async setUserInfo() {
    const { ctx } = this
    const { helper } = ctx
    const { body } = ctx.request

    const keys = ['avatar', 'nickname']
    const newData = helper.validate(body, {
      // required: keys,
      include: keys,
    })

    await ctx.model.User.updateOne({ _id: ctx.state.user.id }, newData)

    ctx.body = {
      code: 0,
      msg: 'success',
    }
  }

  // 发送短信
  async sms() {
    const { ctx } = this
    const { body } = ctx.request

    await this.service.sms.send({
      mobile: body.mobile,
      type: body.type,
    })

    ctx.state.msg = '发送成功'
  }

  // 云店
  async ydLogin() {
    const { ctx } = this
    const { helper } = ctx
    const { body } = ctx.request

    helper.validate(body, {
      required: ['token', 'memberId'],
    })

    const apiOption = {}
    if (body.isTest) apiOption.baseURL = 'https://yd.linkzl.com/api'

    const ydApi = new this.app.YdApi(apiOption)
    const ydUser = await ydApi.login(body.memberId, body.token)

    if (!ydUser.cellPhoneNo) throw '请先绑定手机号'

    // 判断是否注册
    await ctx.model.User.findOneAndUpdate(
      {
        mobile: ydUser.cellPhoneNo,
      },
      {
        mobile: ydUser.cellPhoneNo,
        name: ydUser.userName,
        nickname: ydUser.nickName,
        avatar: ydUser.headPicUrl,
        isOpen: true,
      },
      {
        upsert: true, // 不存在插入
        setDefaultsOnInsert: true, // 允许插入默认值
      }
    )

    const { user, token, exp, expireTime } = await this.service.userAccount.login(
      {},
      {
        mobile: ydUser.cellPhoneNo,
      }
    )

    ctx.session.user = user

    ctx.body = {
      code: 0,
      msg: '登录成功',
      data: {
        user,
        token,
        exp,
        expireTime,
      },
    }
  }
}

module.exports = Controller
